package com.cxg.fairy.ec.sign;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TextInputEditText;
import android.support.v7.widget.AppCompatButton;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cxg.fairy.app.AccountManager;
import com.cxg.fairy.delegates.LatteDelegate;
import com.cxg.fairy.ec.main.EcBottomDelegate;
import com.cxg.fairy.net.RestClient;
import com.cxg.fairy.net.callback.IError;
import com.cxg.fairy.net.callback.ISuccess;
import com.cxg.fairy.util.checkcode.PhoneFormatCheckUtils;
import com.cxg.fairy.util.log.LatteLogger;
import com.cxg.fairy.util.toasty.Toasty;
import com.diabin.latte.ec.R;
import com.diabin.latte.ec.R2;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by CFairy on 2017/11/22
 */

public class SignInDelegate extends LatteDelegate {


    @BindView(R2.id.met_reg_tel)
    TextInputEditText textRegTel = null;

    @BindView(R2.id.met_reg_psw)
    TextInputEditText textRegPsw = null;

    @BindView(R2.id.acb_login_btn)
    AppCompatButton btnLogin = null;

    @OnClick(R2.id.atv_link_reg)
    void onClickReg() {
        getSupportDelegate().start(new SignUpDelegate());
    }

    @OnClick(R2.id.atv_link_getPsw)
    void onClickGetPsw() {
        getSupportDelegate().start(new ResetPwDelegate());
    }

    private ISignListener mISignListener = null;

    @SuppressWarnings("deprecation")
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if (activity instanceof ISignListener) {
            mISignListener = (ISignListener) activity;
        }
    }


    private boolean checkForm() {
        boolean isPass = false;
        String tel = textRegTel.getText().toString();
        String psw = textRegPsw.getText().toString();
        if (!PhoneFormatCheckUtils.isPhoneLegal(tel)) {
            isPass = false;
        } else {
            if (psw.length() > 5 && psw.length() < 20){
                isPass = true;
            } else {
                isPass = false;
            }
        }

        return isPass;
    }

    @Override
    public Object setLayout() {
        return R.layout.delegate_sign_in;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, @NonNull View rootView) {
        textRegTel.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (checkForm()) {
                    setBtnStatus(true);
                } else {
                    setBtnStatus(false);
                }
            }
        });
        textRegPsw.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (checkForm()) {
                    setBtnStatus(true);
                } else {
                    setBtnStatus(false);
                }
            }
        });
    }

    private void setBtnStatus(boolean status){
        if (status){
            btnLogin.setEnabled(true);
            btnLogin.setBackgroundColor(Color.parseColor("#018b18"));
        }else{
            btnLogin.setEnabled(false);
            btnLogin.setBackgroundColor(Color.parseColor("#9c9c9c"));
        }
    }

    @OnClick(R2.id.acb_login_btn)
    void onClickLogin() {
        String tel = textRegTel.getText().toString();
        String psw = textRegPsw.getText().toString();

        InputMethodManager imm = (InputMethodManager) getContext().getSystemService(getContext().INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(textRegTel.getWindowToken(), 0);
        imm.hideSoftInputFromWindow(textRegPsw.getWindowToken(), 0);

        if (checkForm()) {
            RestClient.builder()
                    .url("consumerLogin")
                    .params("username", tel)
                    .params("password",psw)
                    .success(new ISuccess() {
                        @Override
                        public void onSuccess(String response) {
                            LatteLogger.e("USER_PROFILE", response);
                            final int code = JSON.parseObject(response).getInteger("code");
                            final String msg = JSON.parseObject(response).getString("message");
                            final JSONObject obj = JSON.parseObject(response).getJSONObject("data");
                            final JSONObject o = obj.getJSONObject("consumer");
                            if (code == 1) {
                                AccountManager.setSignUUID(obj.getString("uuid"));//存入UUID
                                AccountManager.setSignTEL(o.getString("username"));
                                AccountManager.setSignState(true);
                                Toasty.success(getContext(), "登录成功!", Toast.LENGTH_SHORT, true).show();
                                getSupportDelegate().start(new EcBottomDelegate());
                            }else{
                                Toasty.error(getContext(), "登录失败!"+msg, Toast.LENGTH_SHORT, true).show();
                            }
                        }
                    })
                    .error(new IError() {
                        @Override
                        public void onError(int code, String msg) {
                            Display display = getProxyActivity().getWindowManager().getDefaultDisplay();
                            int height = display.getHeight();
                            Toast t =  Toasty.error(getContext(), "登录失败!"+msg, Toast.LENGTH_SHORT, true);
                            t.setGravity(Gravity.TOP, 0, height / 9);
                            t.show();
                        }
                    })
                    .build()
                    .post();
        } else {
            Toasty.error(getContext(), "输入信息有误!", Toast.LENGTH_LONG, true).show();
        }

    }

}
